package com.zahb.qadx.ui.fragment;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewbinding.ViewBinding;

import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.base.BaseFragmentV2;
import com.zahb.qadx.databinding.FragmentHasCompleteBinding;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.skeleton.RecyclerViewSkeletonScreen;
import com.zahb.qadx.skeleton.Skeleton;
import com.zahb.qadx.ui.adapter.CourseTaskAdapter;
import com.zahb.qadx.ui.view.decoration.MColorDrawable;
import com.zahb.qadx.ui.view.decoration.MDividerItemDecoration;
import com.zahb.qadx.util.CompatHelper;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.Tips;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by： huwei.
 * Data： 2020-10-21.
 * Time： 14:46.
 * Desc：已完成
 */
public class HasCompleteFragment extends BaseFragmentV2 implements OnRefreshLoadMoreListener {
    private RecyclerView recyclerView;
    private SmartRefreshLayout refreshLayout;
    private CourseTaskAdapter courseTaskAdapter;
    private boolean mIsFirstOnResume = true;
    private LinearLayoutCompat llEmpty;
    private RecyclerViewSkeletonScreen mSkeletonScreen;
    private long mSkeletonShowTime;

    @Nullable
    @Override
    public ViewBinding initViewBinding(@NotNull LayoutInflater inflater, @Nullable ViewGroup container) {
        FragmentHasCompleteBinding binding = FragmentHasCompleteBinding
                .inflate(inflater, container, false);
        refreshLayout = binding.refreshLayout;
        recyclerView = binding.recyclerView;
        llEmpty = binding.emptyLayout.llEmpty;
        return binding;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mIsFirstOnResume) {
            //refreshLayout.autoRefresh();
            onRefresh(refreshLayout);
            showSkeleton();
            mIsFirstOnResume = false;
        }
    }

    @Override
    protected void initViews(View rootView) {
        refreshLayout.setOnRefreshLoadMoreListener(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        MDividerItemDecoration itemDecoration = new MDividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL);
        MColorDrawable colorDrawable = new MColorDrawable(CompatHelper.getColor(R.color.gray_999999)).setIntrinsicWidth(1).setIntrinsicHeight(1);
        itemDecoration.setDrawable(colorDrawable);
        itemDecoration.setShowLast(false);
        recyclerView.addItemDecoration(itemDecoration);
        courseTaskAdapter = new CourseTaskAdapter(getActivity(), new ArrayList<>());
        recyclerView.setAdapter(courseTaskAdapter);
        //isVisible(false);
    }

    private void showSkeleton() {
        refreshLayout.setEnableRefresh(false);
        mSkeletonScreen = Skeleton.bind(recyclerView)
                .adapter(courseTaskAdapter)
                .shimmer(true)
                .shimmerMode(RecyclerViewSkeletonScreen.SHIMMER_MODE_ITEM_CHILD)
                .angle(15)
                .frozen(true)
                //.color(R.color.black_333333)
                .duration(1000)
                .count(10)
                .load(R.layout.item_list_curriculum_skeleton)
                .show();
        mSkeletonShowTime = System.currentTimeMillis();
    }

    private void hideSkeleton() {
        if (mSkeletonScreen != null) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - mSkeletonShowTime > Constant.MIN_NETWORK_TIME) {
                refreshLayout.setEnableRefresh(true);
                mSkeletonScreen.hide();
                mSkeletonScreen = null;
                isVisible(courseTaskAdapter.getItemCount() > 0);
            } else {
                addDisposable(Observable.timer(mSkeletonShowTime + Constant.MIN_NETWORK_TIME - currentTime, TimeUnit.MILLISECONDS)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(aLong -> hideSkeleton()));
            }
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.finishLoadMore(1000);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        if (!TextUtils.isEmpty(BaseApplication.getContext().getToken())) {
            addDisposable(RetrofitService.getNetService()
                    .getUserCourse(10, 1)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(response -> {
                        refreshLayout.finishRefresh();
                        if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                            if (response.getData().getList().size()>0){
                                isVisible(true);
                                courseTaskAdapter.setList(response.getData().getList());
                            }else{
                                isVisible(false);
                            }

                        } else {
                            showBindToast(response.getErrorInfo());
                        }
                        hideSkeleton();
                    }, throwable -> {
                        throwable.printStackTrace();
                        refreshLayout.finishRefresh();
                        Tips.RequestError(getActivity());
                        hideSkeleton();
                    }));
        }
    }

    private void isVisible(boolean flag){
        if (recyclerView.getAdapter() instanceof CourseTaskAdapter) {
            if(flag){
                recyclerView.setVisibility(View.VISIBLE);
                llEmpty.setVisibility(View.GONE);
            }else{
                llEmpty.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.GONE);
            }
        }
    }
}
